import axios from 'axios'
import { Message } from 'element-ui'
import { MessageBox } from 'element-ui'
import { getUrl } from '@/utils/dev-ops'
// import store from '@/store'
import Cookies from 'js-cookie'


const prefix = getUrl('WEB')
// const prefix = getUrl('mock')
// create an axios instance
const service = axios.create({
	baseURL: prefix, // url = base url + request url
	withCredentials: false, // send cookies when cross-domain requests
	timeout: 600000, // request timeout
})

// request interceptor
service.interceptors.request.use(
	(config) => {
		// do something before request is sent
      if(!Cookies.get('token')){
        if (config.url.indexOf('/mbl/User/login') === -1){
          Message({
            message: '需要进行校验，请重新登录',
            type: 'error',
            duration: 2000,
            showClose: true
          })
        }
      } else {
        if (config.method === 'post') {
          // let each request carry token --['X-Token'] as a custom key.
          // please modify it according to the actual situation.
          config.headers['token'] = Cookies.get('token')
        }
      }
		return config
	},
	(error) => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	/**
	 * If you want to get information such as headers or status
	 * Please return  response => response
	 */

	/**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code.
	 */
	(response) => {
      const res = response.data
      const is_normal_err = res.message && res.message.length < 50
      if (String(res.result) !== '1') {
        Message({
          message: is_normal_err ? res.message : '返回数据异常',
          type: 'error',
          duration: 2 * 1000
        })
        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
          // to re-login
          MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            location.reload()
            // store.dispatch('user/clearInfo').then(() => {
            //   location.reload()
            // })
          })
        }
        return Promise.reject(res.message || 'error')
      }
      return res
	},
	(error) => {
    if (error.response.status === 401) {
      MessageBox.confirm('登录超时，建议重新登录', '确认重新登录', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        location.reload()
      })
    }
		return Promise.reject(error)
	}
)

export default service
